//
//  PersonInfoViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/8/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import LTScrollView
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class PersonInfoViewController: BaseViewController,PersonHeadViewDelegate {
    var headView: PersonHeadView?
    
    var isMine:Bool = false
    var userId:String?
    var model: commentUserModel?
    
    private lazy var viewControllers: [UIViewController] = {
        let oneVc = PersonCircleViewController()
        oneVc.isMine = isMine
        oneVc.userId = userId
        let twoVc = PersonAViewController()
        twoVc.isMine = isMine
        twoVc.userId = userId
        let threeVc = PersonBViewController()
        threeVc.isMine = isMine
        threeVc.userId = userId
        return [oneVc, twoVc, threeVc]
    }()
    
    private lazy var titles: [String] = {
        return ["圈子", "文章", "视频"]
    }()
    
    private lazy var layout: LTLayout = {
        let layout = LTLayout()
        layout.isAverage = true
        layout.sliderWidth = 20
        layout.isHiddenSlider = false
        layout.titleSelectColor = UIColor.init(r: 255, g: 255, b: 255)
        layout.bottomLineColor = UIColor.init(r: 255, g: 255, b: 255)
        layout.titleViewBgColor = UIColor.init(r: 198, g: 198, b: 198)
        return layout
    }()
    
    private lazy var advancedManager: LTAdvancedManager = {
        let statusBarH = UIApplication.shared.statusBarFrame.size.height
        let Y: CGFloat = 0
        let H: CGFloat = view.bounds.height+64
        let advancedManager = LTAdvancedManager(frame: CGRect(x: 0, y: Y, width: ScreenWidth, height: H), viewControllers: viewControllers, titles: titles, currentViewController: self, layout: layout, headerViewHandle: {[weak self] in
            guard let strongSelf = self else { return UIView() }
            strongSelf.headView = strongSelf.testLabel()
            return strongSelf.headView!
        })
        /* 设置代理 监听滚动 */
        advancedManager.delegate = self
        
        return advancedManager
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        self.automaticallyAdjustsScrollViewInsets = false
        view.addSubview(advancedManager)
        advancedManagerConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        fetchMyUserData()
    }
    
    override func setNavigation() {
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
//    func showToast(msg :String) -> Void {
//        self.view.makeToast("一度蜜：" + msg, duration: 1.5, position: .center)
//    }
    
    @IBAction func editUserInfoAction(_ sender: UIButton) {
        let editingInformationVC = EditingInformationViewController(nibName: "\(EditingInformationViewController.self)", bundle: nil)
        editingInformationVC.userInfo = MineInfoModel.share.userInfModel!
        navigationController?.pushViewController(editingInformationVC, animated: true)
    }
    
//    @IBAction func followBtnAction(_ sender: UIButton) {
//        if sender.isSelected {
//            attentionCancelUser(parameters: ["concernUserId": userId!])
//        }else {
//            attentionUser(parameters: ["concernUserId": userId!])
//        }
//    }
    
    /// 获取圈子列表
    func fetchMyUserData() -> Void {
        var params:[String:String]?
        if userId != nil {
            if MineInfoModel.share.userInfModel?.id != userId {
                params = ["otherUserId":userId!]
            }else {
                isMine = true
            }
        }else{
            isMine = true
        }
        let requesturl = "\(BaseURL)\(userDetailUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: params ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary!
                                        var amodel = commentUserModel(fromDic: dic)
                                        amodel.initGrade(dic: (dic["grade"]?.dictionary)!)
                                        self.model = amodel
                                        if self.isMine {
                                            self.title = "个人主页"
                                        }else {
                                            self.title = self.model?.nickname
                                        }
                                        self.headView?.setData(model:self.model!,isMine: self.isMine)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
    
    func followButtonTap(btn: UIButton) {
        if btn.isSelected {
            attentionCancelUser(parameters: ["concernUserId": userId!],btn:btn)
        }else {
            attentionUser(parameters: ["concernUserId": userId!],btn:btn)
        }
    }
    
    func editUserTap() {
        let editingInformationVC = EditingInformationViewController(nibName: "\(EditingInformationViewController.self)", bundle: nil)
        editingInformationVC.userInfo = MineInfoModel.share.userInfModel!
        navigationController?.pushViewController(editingInformationVC, animated: true)
    }
    
    func userATap() {
        let vc = FansViewController()
        vc.title = "关注"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func userBTap() {
        let vc = FansViewController()
        vc.title = "粉丝"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    /// 关注用户
    func attentionUser(parameters: [String:String],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionUserUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()

                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"关注成功")
                                        btn.isSelected = true
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }

                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"关注失败")
                                print("请求失败\(String(describing: response.error))")
                            }

        }

    }

    /// 取消关注用户
    func attentionCancelUser(parameters: [String:String],btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionCancelUserUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()

                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"取消关注成功")
                                        btn.isSelected = false
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }

                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                                print("请求失败\(String(describing: response.error))")
                            }

        }

    }

}

extension PersonInfoViewController: LTAdvancedScrollViewDelegate {
    
    //MARK: 具体使用请参考以下
    private func advancedManagerConfig() {
        //MARK: 选中事件
        advancedManager.advancedDidSelectIndexHandle = {
            print("选中了 -> \($0)")
        }
        
    }
    
    func glt_scrollViewOffsetY(_ offsetY: CGFloat) {
        //        print("offset --> ", offsetY)
    }
}


extension PersonInfoViewController {
    private func testLabel() -> PersonHeadView {
        let head = PersonHeadView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: self.view.bounds.height/2))
        head.delegate = self
        self.headView = head
        return self.headView!
    }
}
